\documentclass[11pt,a4paper,onecolumn]{article}
\usepackage[utf8]{inputenc}
\usepackage{amsmath}
\usepackage{amsfonts}
\usepackage{amssymb}
\usepackage{graphicx}
\usepackage{colortbl}
\usepackage[T1]{fontenc}
\graphicspath{{img/}} % Specifies the directory where pictures are stored
\usepackage[margin=0.8in]{geometry}
\setlength{\fboxrule}{0.75pt}
\setlength{\fboxsep}{6pt}
\usepackage{listings}
\usepackage[usenames,dvipsnames]{color} % Required for specifying custom colors and referring to colors by name

\definecolor{DarkGreen}{rgb}{0.0,0.4,0.0} % Comment color
\definecolor{highlight}{RGB}{255,251,204} % Code highlight color

\lstdefinestyle{Style1}{ % Define a style for your code snippet, multiple definitions can be made if, for example, you wish to insert multiple code snippets using different programming languages into one document
language=c, % Detects keywords, comments, strings, functions, etc for the language specified
backgroundcolor=\color{highlight}, % Set the background color for the snippet - useful for highlighting
basicstyle=\footnotesize\ttfamily, % The default font size and style of the code
breakatwhitespace=false, % If true, only allows line breaks at white space
breaklines=true, % Automatic line breaking (prevents code from protruding outside the box)
captionpos=b, % Sets the caption position: b for bottom; t for top
commentstyle=\usefont{T1}{pcr}{m}{sl}\color{DarkGreen}, % Style of comments within the code - dark green courier font
deletekeywords={}, % If you want to delete any keywords from the current language separate them by commas
%escapeinside={\%}, % This allows you to escape to LaTeX using the character in the bracket
firstnumber=1, % Line numbers begin at line 1
frame=single, % Frame around the code box, value can be: none, leftline, topline, bottomline, lines, single, shadowbox
frameround=tttt, % Rounds the corners of the frame for the top left, top right, bottom left and bottom right positions
keywordstyle=\color{Blue}\bf, % Functions are bold and blue
morekeywords={}, % Add any functions no included by default here separated by commas
numbers=left, % Location of line numbers, can take the values of: none, left, right
numbersep=10pt, % Distance of line numbers from the code box
numberstyle=\tiny\color{Gray}, % Style used for line numbers
rulecolor=\color{black}, % Frame border color
showstringspaces=false, % Don't put marks in string spaces
showtabs=false, % Display tabs in the code as lines
stepnumber=5, % The step distance between line numbers, i.e. how often will lines be numbered
stringstyle=\color{Purple}, % Strings are purple
tabsize=2, % Number of spaces per tab in the code
}

% Create a command to cleanly insert a snippet with the style above anywhere in the document
\newcommand{\insertcode}[2]{\begin{itemize}\item[]\lstinputlisting[caption=#2,label=#1,style=Style1]{#1}\end{itemize}} % The first argument is the script location/filename and the second is a caption for the listing

%------------------------------------------------------------------------------------------

\author{Martin Metal}
\title{Widget Document View Design}
\begin{document}
\maketitle
\section{Requirements for Widget}
\paragraph{Introduction}
This document outlines the design idea of a widget component for the embedded document viewer. The requirements used for this design as as follows:
\begin{enumerate}
\item The widget does not break the existing page, it smoothly adds the document view and can also full remove itself. No event handlers or another JavaScript fragments are left after closing the view so no memory leaking occurs.
\item The widget offers minimal possible integration interface. Ideally it should provide:
	\begin{enumerate}
		\item loader code exposing a single function only
		\item one public function in the Viewer Widget to trigger viewing
		\item one set of parameters handed over to the hosting page by a dedicated CS module
		\item one anchor element ion the markup that determines the future position of the view component.
	\end{enumerate}
\item The performance of the document viewing is addressed.
	\begin{enumerate}
		\item The widget fully supports caching in the browser. The application code is loaded once per hosting page and does not need to get refreshed among requests for different documents.
		\item The application support early loading. The application is asynchronously built in the background even before a request for document view is triggered. The asynchronously build must not influence the performance of the hosting page. E.g. He hosting page should not wait for view widget to load.
	\end{enumerate}
\item The widget is the base component for HTML5 Viewer. It can be used both as a pure Widget or as a standalone HTML page. The widget is always the underlaying component that in either exposed for integration via the interfaces or embedded inside a dedicated page - HTML5 Viewer frame. 
  \begin{enumerate}
	 \item Widget offers API for integration and consequently solves create/destroy sequence for multiple cycles within the life cycle of the hosting page
	 \item Standalone HTML page embeds the Widget, offer just one HTML call as the integration interface and is designed to show one document only. Multiple instances of HTML page may exist, they have islated browser contexts.
	\end{enumerate}
\end{enumerate}
\pagebreak
\section{Design Outline for Widget}
\subsection{Widget API Structure}
\noindent The design utilizes loader code in combination with the modular pattern - require.js. The loader code is very small and its role is to add the ``require.js'' application to the markup of the hosting container. After this completes, the require.js application is instantiated and enabled the document specific view function. That is pretty much it.\\
\\
\noindent The implementation of this API is split into two dedicated JavaScript segments. First one is loader, which must be available in the application that integrates the Document Viewer. Second is the document show function inside the Document Viewer widget itself.\\
\\
\subsection{API}
\paragraph{Loader} is the first part of the API.  Loader implements the function \textbf{OTCVA.onReady}. It can be directly embedded inside the hosting page or can be referred and stored in a dedicated file. If external script file used, it must be however hosted on the same server that delivers the main HTML page. The reason is that the main application does not know anything about an HTML5 Server or document to display yet.\\
\\
\vspace{9pt}
\framebox[1.05\width][l]{\texttt{\textbf{window.OTCVA.onReady( \textit{HTML5 Viewer Server Host} )}}}
\vspace{9pt}

\noindent is the name of the entry point in the loader. This is the first function to be called and actually must be called before document specific function(s) can be called. Ideally, the function is called as a part of the initialization routine of the hosting page (body onload handler, etc.). \\

\paragraph{Require.js Application} is supposed to expose the second function of the Widget API.\\
\\
\vspace{9pt}
\framebox[1.05\width][l]{\texttt{\textbf{window.OTCVA.showDocument( \textit{document descriptor} )}}}
\vspace{9pt}

\noindent where the document descriptor is a XML structure generated by the CS module. The details about the descriptor are not subject of this document. This function triggers the document display inside the document view. This function is connected to a handler element in the hosting page and is called only if the requested by user. This function is implemented as a part of the HTML Viewer.\\
\\
\subsection{Anchor}
\noindent The hosting container must expose an element, where the Document Viewer gets anchored. Ideally, it is supposed to be top most DIV container around the application logic. The require.js application may be added as the last tag in the body element, thus is does not impact the rendering time of the page. The code snipped posted later in this document uses parameter ``anchor'' as a parameter of the onReadt() function. \\

\section{API Implementation Details}
\noindent The hosting application is expected to include both functions of the API in its code. While the first one \textbf{OTCVA.onReady()} can be called as part of the initialization code, the second one\\
\textbf{OTCVA.showDocument()} shall be attached as a handler to an element in the hosting HTML page. The integrating page additionally needs the loader code. As described earlier, it can be referred or embedded, no difference. It will be just an implementation detail in the WebLingo technology in the CS. The loader code implements one function only, it is the function \textbf{OTCVA.onReady()}.\\

\paragraph{OTCVA.onReady()} function basically does one thing. It dynamically adds the ``require.js'' application to the hosting HTML page. This is technically done by injecting a single HTML element to the hosting page. That element is a special version of SCRIPT tag, having attributes specific to require.js application. By adding that element the whole machinery of loading the Document View application gets triggered. Require.js framework itself controls the procedure and it does not require any additional coding. Require.js basically injects the required libraries and parses the entire application logic. Though it does not show anything. No interaction with the user happens yet, it is solely an initialization of the application code.\\
\\
\noindent First after the require.js application get parsed the handler code triggering the viewing may be activated. That is why it is important to use ``Promise'' construct in the loader. Basically, we have multiple options, either implement it by means of native JavaSctipt and take care about the differences among browsers or we use some library offering support for ``Promise'' pattern. E.g. jQuery. This is the code snipper outlining the idea implemented by mens of pure JavaScript:\\
% Commented out FBOX solution, replaced by listing module <<<

% \fbox{\parbox[c]{0.90\textwidth}{\ttfamily\footnotesize
% var OTCVANamespace = window.OTCVA || (window.OTCVA = \{\} );\\
% OTCVANamespace.loadingCompleted = false;\\
% \\
% OTCVANamespace.onReady = function( server, anchor ) \{\\
% \hspace*{5mm}var script = window.document.getElementById(anchor),\\
% \hspace*{5mm}newjs = window.document.createElement('script');\\
% \\
% \hspace*{5mm}if( OTCVA.loadingCompleted === true ) \{\\
% \hspace*{10mm}return;\\
% \hspace*{5mm}\}\\
% \\
% \hspace*{5mm}	newjs.onload = function () \{\\
% \hspace*{10mm}console.log('Document View Widget loaded, active viewing function'); \\
% \hspace*{5mm}\};\\
% \\
% \hspace*{5mm}newjs.src = 'http://' + server + '/WebViewer/htmlview/js/lib/require.js';\\
% \hspace*{5mm}newjs.setAttribute('data-main',"js/app");\\
% \hspace*{5mm}newjs.setAttribute('id',"OTCVA.MAIN.APP");\\
% \hspace*{5mm}script.parentNode.insertBefore(newjs, script.nextSibling);\\
% \hspace*{5mm}OTCVANamespace.loadingCompleted = true;\\
% \hspace*{5mm}OTCVANamespace.serverName = server;\\
% \}\\
% }}

% >>>
\insertcode{"source/loader.js"}{Loader code example.} % The first argument is the script location/filename and the second is a caption for the listing
\\
\noindent The promise is implemented by means of JavaScript, no third party library required. The snippet shows the implementation for common browsers, does not work in IE family, where the handler has a different name and different internal structure. It is however irrelevant for the idea presented in the snippet.\\

\begin{figure}[h] 
\centering\includegraphics[width=1.0\textwidth]{loader_product.png}
\caption[b]{\footnotesize \textit{Loader Code injects one element in the hosting page, which results into additional dependencies added into the page. Loader adds ``require.js'' application, which is the section 1 in the figure. That in turn triggers parsing of the require.js application, which results into adding dependencies in the main page (undescore, jQuery, etc.). That is section 1 in the figure.}}
\label{fig:loader_product}
\end{figure}

\noindent The hosting page contains the Document View Widget and attaches the function call to activate viewing to an element inside the hosting container. The structure of a simple page after the widget gets loaded shows figure~\ref{fig:loader_product}. The section No.2 in the figure is injected by the loader code. The injection triggers require.js into life, which in turn injects the dependent libraries required by the application in the section 1 and parses the application code. This my take certain time, as the application for document view is not trivial. Current initialization takes almost second already and therefore this process should be done just once per page and then remained in the browser cache for the whole lifetime of the hosting HTML page. The application does not change its code depending on what document is called to display, therefore caching remains effective. That is rather important aspect of this design outline.\\

\paragraph{OTCVA.showDocument()} is the only public function implemented inside the Document View. The function basically does two things:\\
\begin{itemize}
	\item inject a script, whose \textbf{src} attribute points to the server code and transmits the document descriptor to the server. Server renders the document and sends back the JSON Object Literal describing the document being rendered. This object is injected in the hosting page so that the application logic of the Viewer itself can refer it and use it to build its own UI. After this completes,
	\item it triggers automatically ``document show'' via the already instantiated Document Viewer code. The Viewer takes the document details, builds UI and sends it to the screen. 
\end{itemize}

\noindent The document details are injected inside the DOM right after the require.js application. 

\begin{figure}[h]
\centering\includegraphics[width=1.0\textwidth]{loaded_app.png}
\caption[b]{\footnotesize \textit{The document specific descriptor is added to the page. It is achieved by injecting script having the source attribute pointing to the logic of the application server - WebViewer server.}}
\label{fig:loader_code}
\end{figure}

\end{document}

